package com.youlu.campus.web.config.filter;

import com.youlu.campus.web.config.filter.utils.ResponseUtils;
import com.yuelin.infrastructure.quantum.common.QResult;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 保活
 *
 * @Description: KeepAlivedFilter
 * @Date 2025/8/11
 * @module KeepAlivedFilter
 * @author: su
 */
public class KeepAlivedFilter extends OncePerRequestFilter {

    private static final String KEEP_ALIVED_URL = "/";

    private final String prefix;

    public KeepAlivedFilter(String prefix) {
        this.prefix = prefix;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //检查url路径
        String url = request.getServletPath();
        if (url.contains(prefix)) {
            url = url.replaceFirst(prefix, "");
        }
        // 心跳检测
        if (KEEP_ALIVED_URL.equals(url)) {
            ResponseUtils.writeOutJson(response, QResult.success(true));
            return;
        }
        filterChain.doFilter(request, response);
    }
}
